<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>教师管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <style>
        .form-container {
            display: none;
            margin-top: 20px;
            padding: 20px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            background-color: #f8f9fa;
        }
        .active-form {
            display: block;
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(0,0,0,.3);
            border-radius: 50%;
            border-top-color: #007bff;
            animation: spin 1s ease-in-out infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .course-badge {
            margin-right: 5px;
            margin-bottom: 5px;
            display: inline-block;
        }
        .action-buttons {
            white-space: nowrap;
        }
        .pagination {
            margin: 20px 0;
            justify-content: center;
        }
        .page-item.active .page-link {
            background-color: #0d6efd;
            border-color: #0d6efd;
        }
        .page-link {
            color: #0d6efd;
        }
        .page-item.disabled .page-link {
            color: #6c757d;
        }
        .search-container {
            margin-bottom: 20px;
        }
        .table-container {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>教师管理系统</h2>
        <button id="btnAddTeacher" class="btn btn-primary">新增教师</button>
    </div>

    <div class="card search-container">
        <div class="card-body">
            <div class="input-group">
                <input type="text" id="searchName" class="form-control" placeholder="输入教师姓名查询">
                <button id="btnSearch" class="btn btn-outline-secondary">查询</button>
                <button id="btnReset" class="btn btn-outline-secondary">重置</button>
            </div>
        </div>
    </div>

    <div class="card table-container">
        <div class="card-body p-0">
            <div id="teacherList">
                <div class="table-responsive">
                    <table class="table table-striped table-hover mb-0">
                        <thead class="table-dark">
                        <tr>
                            <th>教师编号</th>
                            <th>姓名</th>
                            <th>院系</th>
                            <th>邮箱</th>
                            <th>电话</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody id="teacherTableBody">
                        <!-- 数据将通过Ajax动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <nav aria-label="Page navigation">
        <ul class="pagination" id="pagination">
            <!-- 分页按钮将通过JS动态生成 -->
        </ul>
    </nav>

    <div id="teacherForm" class="form-container">
        <h3 id="formTitle">新增教师</h3>
        <form id="teacherFormElement">
            <input type="hidden" id="teacherId" name="teacherNo">

            <div class="mb-3">
                <label for="teacherNo" class="form-label">教师编号</label>
                <input type="number" class="form-control" id="teacherNo" name="teacherNo" required>
            </div>

            <div class="mb-3">
                <label for="name" class="form-label">姓名</label>
                <input type="text" class="form-control" id="name" name="name" required>
            </div>

            <div class="mb-3">
                <label for="department" class="form-label">院系</label>
                <input type="text" class="form-control" id="department" name="department" required>
            </div>

            <div class="mb-3">
                <label for="email" class="form-label">邮箱</label>
                <input type="email" class="form-control" id="email" name="email">
            </div>

            <div class="mb-3">
                <label for="phone" class="form-label">电话</label>
                <input type="tel" class="form-control" id="phone" name="phone">
            </div>

            <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                <button type="submit" class="btn btn-primary me-md-2">保存</button>
                <button type="button" id="btnCancel" class="btn btn-secondary">取消</button>
            </div>
        </form>
    </div>
</div>

<script>
    $(document).ready(function() {
        // 状态管理
        const state = {
            currentPage: 1,
            pageSize: 10,
            totalRecords: 0,
            totalPages: 1,
            currentSearch: ''
        };

        // 页面加载时获取教师数据
        loadTeachers();

        // 新增教师按钮点击事件
        $('#btnAddTeacher').click(function() {
            showForm('新增教师');
            resetForm();
        });

        // 查询按钮点击事件
        $('#btnSearch').click(function() {
            state.currentSearch = $('#searchName').val().trim();
            state.currentPage = 1;
            loadTeachers();
        });

        // 重置按钮点击事件
        $('#btnReset').click(function() {
            $('#searchName').val('');
            state.currentSearch = '';
            state.currentPage = 1;
            loadTeachers();
        });

        // 取消按钮点击事件
        $('#btnCancel').click(hideForm);

        // 表单提交事件
        $('#teacherFormElement').submit(function(e) {
            e.preventDefault();
            saveTeacher();
        });

        // 编辑和删除按钮事件委托
        $(document).on('click', '.btn-edit', function() {
            const teacherNo = $(this).data('id');
            loadTeacherData(teacherNo);
        });

        $(document).on('click', '.btn-delete', function() {
            const teacherNo = $(this).data('id');
            if (confirm('确定要删除此教师吗？')) {
                deleteTeacher(teacherNo);
            }
        });

        // 加载教师数据
        function loadTeachers() {
            $('#teacherTableBody').html(`
            <tr>
                <td colspan="6" class="text-center">
                    <div class="loading"></div> 加载中...
                </td>
            </tr>
        `);

            let url = `/teacher/getAll?current=${state.currentPage}&size=${state.pageSize}`;
            if (state.currentSearch) {
                url += `&name=${encodeURIComponent(state.currentSearch)}`;
            }

            $.ajax({
                url: url,
                type: 'GET',
                success: function(data) {
                    if (data && data.code === '200') {
                        renderTeacherTable(data.data.list || []);
                        state.totalRecords = data.data.total;
                        state.totalPages = data.data.pages;
                        renderPagination();
                    } else {
                        throw new Error(data?.msg || '获取教师数据失败: 响应格式不正确');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('加载教师数据出错:', error);
                    $('#teacherTableBody').html(`
                    <tr>
                        <td colspan="6" class="text-center text-danger">
                            加载失败: ${xhr.responseJSON?.msg || error}
                        </td>
                    </tr>
                `);
                }
            });
        }

        // 渲染教师表格
        function renderTeacherTable(teachers) {
            if (!Array.isArray(teachers)) {
                $('#teacherTableBody').html(`
                <tr>
                    <td colspan="6" class="text-center py-4">
                        教师数据格式错误
                    </td>
                </tr>
            `);
                return;
            }

            if (teachers.length === 0) {
                $('#teacherTableBody').html(`
                <tr>
                    <td colspan="6" class="text-center py-4">
                        ${state.currentSearch ? '没有找到匹配的教师' : '暂无教师数据'}
                    </td>
                </tr>
            `);
                return;
            }

            let html = '';
            teachers.forEach(teacher => {
                html += `
                <tr data-id="${teacher.teacherNo}">
                    <td>${teacher.teacherNo}</td>
                    <td>${teacher.name}</td>
                    <td>${teacher.department || '-'}</td>
                    <td>${teacher.email || '-'}</td>
                    <td>${teacher.phone || '-'}</td>
                    <td class="action-buttons">
                        <button data-id="${teacher.teacherNo}" class="btn-edit btn btn-sm btn-outline-primary">编辑</button>
                        <button data-id="${teacher.teacherNo}" class="btn-delete btn btn-sm btn-outline-danger">删除</button>
                    </td>
                </tr>
            `;
            });

            $('#teacherTableBody').html(html);
        }

        // 渲染分页控件
        function renderPagination() {
            const $pagination = $('#pagination');
            $pagination.empty();

            // 上一页按钮
            const prevDisabled = state.currentPage === 1 ? 'disabled' : '';
            $pagination.append(`
            <li class="page-item ${prevDisabled}">
                <a class="page-link" href="#" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
        `);

            // 页码按钮
            const maxVisiblePages = 5;
            let startPage = Math.max(1, state.currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(state.totalPages, startPage + maxVisiblePages - 1);

            if (endPage - startPage + 1 < maxVisiblePages) {
                startPage = Math.max(1, endPage - maxVisiblePages + 1);
            }

            // 第一页按钮（如果需要）
            if (startPage > 1) {
                $pagination.append(`
                <li class="page-item">
                    <a class="page-link" href="#">1</a>
                </li>
            `);

                if (startPage > 2) {
                    $pagination.append(`
                    <li class="page-item disabled">
                        <span class="page-link">...</span>
                    </li>
                `);
                }
            }

            // 中间页码按钮
            for (let i = startPage; i <= endPage; i++) {
                const active = i === state.currentPage ? 'active' : '';
                $pagination.append(`
                <li class="page-item ${active}">
                    <a class="page-link" href="#">${i}</a>
                </li>
            `);
            }

            // 最后一页按钮（如果需要）
            if (endPage < state.totalPages) {
                if (endPage < state.totalPages - 1) {
                    $pagination.append(`
                    <li class="page-item disabled">
                        <span class="page-link">...</span>
                    </li>
                `);
                }

                $pagination.append(`
                <li class="page-item">
                    <a class="page-link" href="#">${state.totalPages}</a>
                </li>
            `);
            }

            // 下一页按钮
            const nextDisabled = state.currentPage === state.totalPages ? 'disabled' : '';
            $pagination.append(`
            <li class="page-item ${nextDisabled}">
                <a class="page-link" href="#" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        `);

            // 绑定分页点击事件
            $pagination.find('.page-link').click(function(e) {
                e.preventDefault();
                const $li = $(this).closest('li');
                if ($li.hasClass('disabled')) return;

                const text = $(this).text().trim();
                if (text === '«') {
                    state.currentPage--;
                } else if (text === '»') {
                    state.currentPage++;
                } else if (text === '...') {
                    return;
                } else {
                    state.currentPage = parseInt(text);
                }
                loadTeachers();
            });
        }

        // 加载单个教师数据
        function loadTeacherData(teacherNo) {
            $.ajax({
                url: `/teacher/${teacherNo}`,
                type: 'GET',
                success: function(data) {
                    if (data.code === '200') {
                        showForm('编辑教师');
                        $('#teacherId').val(data.data.teacherNo);
                        $('#teacherNo').val(data.data.teacherNo);
                        $('#name').val(data.data.name || '');
                        $('#department').val(data.data.department || '');
                        $('#email').val(data.data.email || '');
                        $('#phone').val(data.data.phone || '');
                        $('#teacherNo').prop('readonly', true);
                    } else {
                        throw new Error(data.msg || '获取教师数据失败');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error);
                    alert('获取教师数据失败: ' + (xhr.responseJSON?.msg || error));
                }
            });
        }

        // 保存教师信息
        function saveTeacher() {
            // 数据验证
            if (!$('#teacherNo').val() || isNaN(parseInt($('#teacherNo').val()))) {
                alert('请输入有效的教师编号');
                return;
            }
            if (!$('#name').val().trim()) {
                alert('教师姓名不能为空');
                return;
            }
            if (!$('#department').val().trim()) {
                alert('所属院系不能为空');
                return;
            }

            const teacherData = {
                teacherNo: parseInt($('#teacherNo').val()),
                name: $('#name').val().trim(),
                department: $('#department').val().trim(),
                email: $('#email').val().trim() || null,
                phone: $('#phone').val().trim() || null
            };

            // 显示加载状态
            const $saveBtn = $('#teacherFormElement').find('button[type="submit"]');
            const originalBtnText = $saveBtn.html();
            $saveBtn.prop('disabled', true);
            $saveBtn.html('<span class="loading"></span> 保存中...');

            $.ajax({
                url: '/teacher/save',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(teacherData),
                success: function(data) {
                    if (data.code === '200') {
                        alert(data.msg || '保存成功');
                        hideForm();
                        loadTeachers();
                    } else {
                        throw new Error(data.msg || '保存失败');
                    }
                },
                error: function(xhr, status, error) {
                    const errorMsg = xhr.responseJSON?.msg || error;
                    console.error('保存失败:', errorMsg);
                    alert(errorMsg.includes('Duplicate')
                        ? '教师编号已存在，请使用其他编号'
                        : errorMsg);
                },
                complete: function() {
                    $saveBtn.prop('disabled', false);
                    $saveBtn.html(originalBtnText);
                }
            });
        }

        // 删除教师
        function deleteTeacher(teacherNo) {
            $.ajax({
                url: `/teacher/${teacherNo}`,
                type: 'DELETE',
                success: function(data) {
                    if (data.code === '200') {
                        alert('删除成功');
                        loadTeachers();
                    } else {
                        throw new Error(data.msg || '删除失败');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error:', error);
                    alert('删除失败: ' + (xhr.responseJSON?.msg || error));
                }
            });
        }

        // 显示表单
        function showForm(title) {
            $('#formTitle').text(title);
            $('#teacherList').hide();
            $('#teacherForm').addClass('active-form');
            $('#btnAddTeacher').hide();
        }

        // 隐藏表单
        function hideForm() {
            $('#teacherList').show();
            $('#teacherForm').removeClass('active-form');
            $('#btnAddTeacher').show();
        }

        // 重置表单
        function resetForm() {
            $('#teacherFormElement')[0].reset();
            $('#teacherNo').prop('readonly', false);
        }
    });
</script>
</body>
</html>